package com.hnevc.restaurant.annotation.auth;

import java.io.PrintWriter;
import java.util.Set;

import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;

public class AuthInterceptor extends HandlerInterceptorAdapter {
	
	public static final String K_USERID = "kUSERID";
	public static final String SESSION_AUTHS = "kAUTHS";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		boolean flag = true;
		if(handler instanceof HandlerMethod) {
			Auth auth =((HandlerMethod)handler).getMethod().getAnnotation(Auth.class);
			if(auth !=null) {
				if(request.getSession().getAttribute(K_USERID) == null) {
					//没有登陆
					//设置状态码为403，拒绝访问
					response.setStatus(HttpStatus.FORBIDDEN.value());
					response.setContentType("text/html; charset=UTF-8"); 
					PrintWriter out=response.getWriter();  
					out.write("{\"type\":\"nosignin\",\"msg\":\"请您先登录!\"}");  
	                out.flush();  
	                out.close();
				}
				else {
					if (!"".equals(auth.value())) {  
                        Set<String> auths = (Set<String>) request.getSession().getAttribute(SESSION_AUTHS);  
                        if (!auths.contains(auth.value())) {// 提示用户没权限  
                            response.setStatus(HttpStatus.FORBIDDEN.value());  
                            response.setContentType("text/html; charset=UTF-8");  
                            PrintWriter out=response.getWriter();  
                            out.write("{\"type\":\"noauth\",\"msg\":\"您没有"+auth.name()+"权限!\"}");  
                            out.flush();  
                            out.close();  
                            flag = false;  
                        }  
                    }  
				}
			}
		}
		return flag;
	}

}
